package com.agileai.portal.controller.mobile;

import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.frame.SecurityAuthorizationConfig;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.auth.SecurityUserMobileManage;
import com.agileai.util.CryptionUtil;
import com.agileai.util.MapUtil;
import com.agileai.util.StringUtil;

public class WxConfigHandler extends BaseHandler{
	
	@PageAction
	public ViewRenderer wxBinding(DataParam param){
		String responseText = FAIL;
		try {
    		String inputString = this.getInputString();
        	JSONObject jsonObject = new JSONObject(inputString);
    		
        	String userCode = jsonObject.get("userCode").toString();
    		String userPwd = jsonObject.get("userPwd").toString();
    		
    		String valideCode = jsonObject.get("valideCode").toString();
    		String safecode = (String)this.request.getSession().getAttribute("safecode");
    		if (!valideCode.equals(safecode)){
    			responseText = "验证码不正确，请检查！";
    		}else{
    			SecurityAuthorizationConfig authorizationConfig = (SecurityAuthorizationConfig)this.lookupService("securityAuthorizationConfigService");
    			DataRow userRow = authorizationConfig.retrieveUserRecord(userCode);
    			if (MapUtil.isNullOrEmpty(userRow)){
    				responseText = "该用户不存在！";
    			}else{
    				String userPwdTemp = String.valueOf(userRow.get("USER_PWD"));
    				String encryptedPassword = CryptionUtil.md5Hex(userPwd);
    				if (userPwdTemp.equals(encryptedPassword)){
    					SecurityUserMobileManage securityUserMobileManage = this.lookupService(SecurityUserMobileManage.class);
    					String wxOpenId = (String)this.getSessionAttribute("openId");
    					if (StringUtil.isNotNullNotEmpty(wxOpenId)){
        					securityUserMobileManage.bindUserWxOpenId(userCode, wxOpenId);
        					responseText = SUCCESS;    						
    					}else{
    						responseText = "没有获取到微信标识！";	
    					}
    				}
    				else{
    					responseText = "用户ID或者密码不正确！";
    				}
    			}			
    		}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return new AjaxRenderer(responseText);
	}
	
	@PageAction
	public ViewRenderer wxUnbundling(DataParam param){
		String responseText = FAIL;
		try {
			SecurityUserMobileManage securityUserMobileManage = this.lookupService(SecurityUserMobileManage.class);
			User user = (User) getUser();
			securityUserMobileManage.unbindUserWxOpenId(user.getUserCode());
			responseText = SUCCESS;
		} catch (Exception e) {
			log.error(e.getLocalizedMessage());
		}
		return new AjaxRenderer(responseText);
	}
	
}
